from typing import Dict, Any
import json
import os
from .base import BaseModel
from .openai_compatible import OpenAICompatibleModel
from .deepseek import DeepSeekModel
from .claude import ClaudeModel

class ModelFactory:
    """模型工厂类，负责创建和管理不同的模型实例"""
    
    @staticmethod
    def create_model(model_config: Dict[str, Any]) -> BaseModel:
        """根据配置创建模型实例
        
        Args:
            model_config: 模型配置字典，包含api_url、model_name、api_key等信息
            
        Returns:
            对应的模型实例
        """
        model_name = model_config["model_name"].lower()
        api_key = model_config["api_key"]
        api_url = model_config["api_url"]
        
        if "claude" in model_name:
            return ClaudeModel(api_key, model_name, api_url)
        elif "deepseek" in model_name:
            return DeepSeekModel(api_key, model_name, api_url)
        else:
            return OpenAICompatibleModel(api_key, model_name, api_url)
    
    @staticmethod
    def get_model_configs() -> Dict[str, Dict[str, Any]]:
        """从JSON配置文件获取模型配置"""
        try:
            # 获取当前文件的目录
            current_dir = os.path.dirname(os.path.abspath(__file__))
            # 构建配置文件路径
            config_path = os.path.join(current_dir, '..', 'config', 'models.json')
            config_path = os.path.normpath(config_path)
            
            # 读取JSON配置文件
            with open(config_path, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
            
            # 返回模型配置
            return config_data.get('models', {})
            
        except FileNotFoundError:
            print(f"配置文件未找到: {config_path}")
            return {}
        except json.JSONDecodeError as e:
            print(f"JSON配置文件解析错误: {e}")
            return {}
        except Exception as e:
            print(f"读取配置文件时发生错误: {e}")
            return {}
    
    @staticmethod
    def get_current_model() -> str:
        """从JSON配置文件获取当前选中的模型"""
        try:
            # 获取当前文件的目录
            current_dir = os.path.dirname(os.path.abspath(__file__))
            # 构建配置文件路径
            config_path = os.path.join(current_dir, '..', 'config', 'models.json')
            config_path = os.path.normpath(config_path)
            
            # 读取JSON配置文件
            with open(config_path, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
            
            return config_data.get('current_model', 'Moonshot-V1-8K')
            
        except Exception as e:
            print(f"读取当前模型配置时发生错误: {e}")
            return 'Moonshot-V1-8K'
    
    @staticmethod
    def set_current_model(model_name: str) -> bool:
        """设置当前选中的模型到JSON配置文件"""
        try:
            # 获取当前文件的目录
            current_dir = os.path.dirname(os.path.abspath(__file__))
            # 构建配置文件路径
            config_path = os.path.join(current_dir, '..', 'config', 'models.json')
            config_path = os.path.normpath(config_path)
            
            # 读取现有配置
            with open(config_path, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
            
            # 更新当前模型
            config_data['current_model'] = model_name
            
            # 写回文件
            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, ensure_ascii=False, indent=4)
            
            return True
            
        except Exception as e:
            print(f"设置当前模型时发生错误: {e}")
            return False